<?php

/**
 * Sunny软件公司欲开发一个多功能文档编辑器，在文本文档中可以插入图片、动画、视频等多媒体资料，
 * 为了节约系统资源，相同的图片、动画和视频在同一个文档中只需保存一份，但是可以多次重复出现，
 * 而且它们每次出现时位置和大小均可不同。试使用享元模式设计该文档编辑器。
 */

/**
 * 多媒体资料类：抽象享元类
 */
abstract class Media
{
	protected $name;
	protected $size;
	
	public function __construct($name, $size)
	{
		$this->name = $name;
		$this->size = $size;
	}
	
	public abstract function getType();
	
	public function show(Additional $additional)
	{
		echo "类型：{$this->getType()} 名称：{$this->name} 大小：{$this->size} 位置：{$additional->getX()},{$additional->getY()} 宽高：{$additional->getWidth()},{$additional->getHeight()}<br/>";
	}
}

/**
 * 图片：具体享元类
 */
class Image extends Media
{
	public function getType()
	{
		return '图片';
	}
}

/**
 * 动画：具体享元类
 */
class Animation extends Media
{
	public function getType()
	{
		return '动画';
	}
}

/**
 * 视频：具体享元类
 */
class Video extends Media
{
	public function getType()
	{
		return '视频';
	}
}

/**
 * 多媒体工厂类：享元工厂类
 */
class MediaFactory
{
	private $_medias;
	
	public function __construct()
	{
		$this->_medias = array();
	}
	
	public function getMedia(Media $media)
	{
		$index = array_search($media, $this->_medias);
		if ($index !== false) {
			return $this->_medias[$index];
		}
		$this->_medias[] = $media;
		return $media;
	}
}

/**
 * 位置和大小
 */
class Additional
{
	private $_x;
	private $_y;
	private $_width;
	private $_height;
	
	public function __construct($x, $y, $width, $height)
	{
		$this->_x = $x;
		$this->_y = $y;
		$this->_width = $width;
		$this->_height = $height;
	}
	
	public function setX($x)
	{
		$this->_x = $x;
	}
	
	public function getX()
	{
		return $this->_x;
	}
	
	public function setY($y)
	{
		$this->_y = $y;
	}
	
	public function getY()
	{
		return $this->_y;
	}
	
	public function setWidth($width)
	{
		$this->_width = $width;
	}
	
	public function getWidth()
	{
		return $this->_width;
	}
	
	public function setHeight($heigth)
	{
		$this->_height = $heigth;
	}
	
	public function getHeight()
	{
		return $this->_height;
	}
}

class Client
{
	public static function main()
	{
		$factory = new MediaFactory();
		
		$image1 = new Image('image1', '500kb');
		$image2 = new Image('image2', '5M');
		$animation1 = new Animation('animation1', '10M');
		$video1 = new Video('video1', '20M');
		
		$media1 = $factory->getMedia($image1);
		$media2 = $factory->getMedia($image1);
		$media3 = $factory->getMedia($image1);
		
		$media1->show(new Additional(11, 22, 100, 100));
		$media2->show(new Additional(10, 20, 200, 200));
		
		echo $media1 === $media2 ? '相同' : '不同';
	}
}

client::main();